﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Web;

namespace SPPTesteGeral.VWPFormLoginASP
{
    public partial class VWPFormLoginASPUserControl : UserControl
    {
        string nomeUsuario = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        #region EVENTOS;

        protected void loginASP_Authenticate(object sender, AuthenticateEventArgs e)
        {
            bool isAuthenticate = false;
            isAuthenticate = LoginUsuario(loginASP.UserName, loginASP.Password);
            e.Authenticated = isAuthenticate;
            if (isAuthenticate) SPUtility.Redirect("BemvindoHome.aspx", SPRedirectFlags.Default, HttpContext.Current);
        }
        #endregion
        #region METODOS

        private bool LoginUsuario(string userName, string userPass)
        {
            using (SPWeb myWeb = SPContext.Current.Site.RootWeb)
            {
                SPList myList = myWeb.Lists["Usuario"];

                SPQuery myQuery = new SPQuery();
                myQuery.Query = string.Format(@"<Where><And>
                                <Eq><FieldRef Name='Title' />
                                    <Value Type='Text'>{0}</Value></Eq>
                                <Eq><FieldRef Name='Senha' />
                                    <Value Type='Text'>{1}</Value></Eq>
                                </And></Where>", userName, userPass);

                SPListItemCollection mycollection = myList.GetItems(myQuery);
                if (mycollection != null)
                {
                    if (mycollection.Count > 0)
                    {
                        nomeUsuario = mycollection.Fields["Title"].ToString();
                        //Session["nomeUsuario"] = nomeUsuario;
                    }

                    return mycollection.Count > 0;
                }
                else return false; ;
            }
        }

        #endregion
    }
}